import { requestClient } from '#/api/request';

/**
 * IP安全规则类型
 */
export type RuleType = 'WHITELIST' | 'BLACKLIST' | 'RATE_LIMIT';

/**
 * 目标类型
 */
export type TargetType = 'GLOBAL' | 'API' | 'USER';

/**
 * 动作类型
 */
export type ActionType = 'ALLOW' | 'DENY' | 'BLOCK';

/**
 * IP安全规则接口
 */
export interface IpSecurityRule {
  id: number;
  name: string;
  ipPattern: string;
  ruleType: RuleType;
  targetType: TargetType;
  targetValue?: string;
  description: string;
  action: ActionType;
  enabled: boolean;
  maxRequestsPerMinute?: number;
  maxRequestsPerHour?: number;
  maxRequestsPerDay?: number;
  createTime: number;
  updateTime: number;
}

/**
 * IP安全规则列表结果
 */
export interface IpSecurityRuleListResult {
  total: number;
  items: IpSecurityRule[];
}

/**
 * IP统计数据-每日统计
 */
export interface DailyStats {
  date: string;
  requests: number;
  blocked: number;
  allowed: number;
}

/**
 * IP统计数据-每小时统计
 */
export interface HourlyStats {
  hour: number;
  requests: number;
  blocked: number;
  allowed: number;
}

/**
 * IP访问统计接口
 */
export interface IpStatistics {
  ipAddress: string;
  totalRequests: number;
  blockedRequests: number;
  allowedRequests: number;
  lastAccessTime: number;
  dailyStats: DailyStats[];
  hourlyStats: HourlyStats[];
}

/**
 * IP验证结果接口
 */
export interface ValidationResult {
  allowed: boolean;
  reason: string;
  action: string;
  matchedRule?: Partial<IpSecurityRule>;
}

/**
 * 频率限制结果接口
 */
export interface RateLimitResult {
  allowed: boolean;
  reason: string;
  remainingRequests: number;
  resetTime: number;
  currentCount: {
    minute: number;
    hour: number;
    day: number;
  };
  limits: {
    minute: number;
    hour: number;
    day: number;
  };
}

/**
 * 安全概览接口
 */
export interface SecurityOverview {
  totalRules: number;
  activeRules: number;
  whitelistedIps: number;
  blacklistedIps: number;
  rateLimitRules: number;
  todayBlocked: number;
  todayAllowed: number;
  lastCleanup: number;
}

/**
 * 清理记录结果接口
 */
export interface CleanupResult {
  deletedCount: number;
  message: string;
}

export namespace IpSecurityApi {
  /**
   * 规则过滤条件接口
   */
  export interface RuleFilters {
    ruleType?: RuleType;
    targetType?: TargetType;
    enabled?: boolean;
    ipPattern?: string;
  }

  /**
   * 分页查询参数
   */
  export interface PageFetchParams {
    page: number;
    pageSize: number;
    ruleType?: RuleType;
    targetType?: TargetType;
    enabled?: boolean;
    ipPattern?: string;
  }

  /**
   * 保存规则参数
   */
  export interface SaveParams {
    id?: number;
    name: string;
    ipPattern: string;
    ruleType: RuleType;
    targetType: TargetType;
    targetValue?: string;
    description?: string;
    action: ActionType;
    enabled: boolean;
    maxRequestsPerMinute?: number;
    maxRequestsPerHour?: number;
    maxRequestsPerDay?: number;
  }
}

/**
 * 获取IP安全规则列表
 * @param params 过滤条件
 * @returns IP安全规则列表
 */
export async function getRulesApi(params?: IpSecurityApi.RuleFilters) {
  return requestClient.post<{
    page: number;
    pageSize: number;
    items: IpSecurityRule[];
    total: number;
  }>('/security/ip/list', params);
}

/**
 * 获取IP安全规则列表（分页）
 * @param params 分页和过滤条件
 * @returns IP安全规则列表（分页）
 */
export async function getRulesPageApi(params: IpSecurityApi.PageFetchParams) {
  return requestClient.get<IpSecurityRuleListResult>('/security/ip/rules/page', { params });
}

/**
 * 获取单个IP安全规则详情
 * @param id 规则ID
 * @returns IP安全规则详情
 */
export async function getRuleDetailApi(id: number) {
  return requestClient.get<IpSecurityRule>(`/security/ip/rules/${id}`);
}

/**
 * 保存IP安全规则（新增或更新）
 * @param data IP安全规则
 * @returns 保存后的IP安全规则
 */
export async function saveRuleApi(data: IpSecurityApi.SaveParams) {
  return requestClient.post<IpSecurityRule>('/security/ip/save', data);
}

/**
 * 删除IP安全规则
 * @param id 规则ID
 */
export async function deleteRuleApi(id: number) {
  return requestClient.delete(`/security/ip/delete/${id}`);
}

/**
 * 批量删除IP安全规则
 * @param ids 规则ID数组
 */
export async function batchDeleteRulesApi(ids: number[]) {
  return requestClient.delete('/security/ip/rules', { data: { ids } });
}

/**
 * 启用/禁用IP安全规则
 * @param id 规则ID
 * @param enabled 是否启用
 */
export async function updateRuleStatusApi(id: number, enabled: boolean) {
  return requestClient.put(`/security/ip/rules/${id}/status`, { enabled });
}

/**
 * 获取IP访问统计
 * @param ipAddress IP地址
 * @param days 统计天数，默认7天
 * @returns IP访问统计信息
 */
export async function getIpStatisticsApi(ipAddress: string, days = 7) {
  return requestClient.get<IpStatistics>(`/security/ip/statistics/${ipAddress}`, { params: { days } });
}

/**
 * 清理过期记录
 * @param days 保留天数，默认30天
 * @returns 清理结果
 */
export async function cleanupRecordsApi(days = 30) {
  return requestClient.post<CleanupResult>('/security/ip/cleanup', null, { params: { days } });
}

/**
 * IP访问验证
 * @param ipAddress IP地址
 * @param apiPath API路径
 * @param username 用户名（可选）
 * @returns 验证结果
 */
export async function validateIpAccessApi(ipAddress: string, apiPath: string, username?: string) {
  const params = { ipAddress, apiPath, username };
  return requestClient.post<ValidationResult>('/security/ip/validate', null, { params });
}

/**
 * 频率限制检查
 * @param ipAddress IP地址
 * @param apiPath API路径
 * @param username 用户名（可选）
 * @returns 频率限制检查结果
 */
export async function checkRateLimitApi(ipAddress: string, apiPath: string, username?: string) {
  const params = { ipAddress, apiPath, username };
  return requestClient.post<RateLimitResult>('/security/ip/rate-limit', null, { params });
}

/**
 * 获取IP安全概览
 * @returns 安全概览信息
 */
export async function getSecurityOverviewApi() {
  return requestClient.get<SecurityOverview>('/security/ip/overview');
}

/**
 * 获取黑名单规则
 * @param enabledOnly 是否只获取启用的规则
 * @returns 黑名单规则列表
 */
export async function getBlacklistRulesApi(enabledOnly = true) {
  return getRulesApi({
    ruleType: 'BLACKLIST',
    enabled: enabledOnly ? true : undefined,
  });
}

/**
 * 获取白名单规则
 * @param enabledOnly 是否只获取启用的规则
 * @returns 白名单规则列表
 */
export async function getWhitelistRulesApi(enabledOnly = true) {
  return getRulesApi({
    ruleType: 'WHITELIST',
    enabled: enabledOnly ? true : undefined,
  });
}

/**
 * 获取频率限制规则
 * @param enabledOnly 是否只获取启用的规则
 * @returns 频率限制规则列表
 */
export async function getRateLimitRulesApi(enabledOnly = true) {
  return getRulesApi({
    ruleType: 'RATE_LIMIT',
    enabled: enabledOnly ? true : undefined,
  });
}